package com.shanzmoo.stm.admin.filter;

import cn.hutool.core.util.StrUtil;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.constant.ErrorCode;
import com.shanzmoo.base.exception.AuthException;
import com.shanzmoo.base.util.SResponseUtils;
import com.shanzmoo.core.manager.JwtManager;
import com.shanzmoo.core.util.JwtUtils;
import com.shanzmoo.core.util.RedisCoreKeyUtils;
import com.shanzmoo.stm.admin.service.AuthUserDetailsService;
import com.shanzmoo.stm.admin.util.RedisKeyUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author: Gzhao 2020/11/9
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final String LOGIN_URI = "/auth/login";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AuthUserDetailsService authUserDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String headerToken = JwtUtils.getJwtFromRequest(request);
        log.info("uri: {}, headerToken: {}", request.getRequestURI(), headerToken);

        if (StrUtil.isNotBlank(headerToken) && !LOGIN_URI.equals(request.getRequestURI())) {
            try {
                String username = getUsernameFromJWT(headerToken);

                UserDetails userDetails = authUserDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (Exception e) {
                log.error("spring security 校验异常", e);
                SResponseUtils.outputJson(response, SResponse.fail(ErrorCode.JWT_VALIDATE_FAIL));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 从jwt 中解析出 用户名
     * @param jwt
     * @return
     */
    private String getUsernameFromJWT(String jwt) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(Constant.JWT_KEY)
                    .parseClaimsJws(jwt)
                    .getBody();

            String redisKey = RedisKeyUtils.installSubectJwtKey(claims.getSubject());

            // 校验redis中的JWT是否存在
            Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS);
            if (Objects.isNull(expire) || expire <= 0) {
                throw new AuthException("Token 不存在或已过期");
            }

            // 校验redis中的JWT是否与当前的一致，不一致则代表用户已注销/用户在不同设备登录，均代表JWT已过期
            String redisToken = stringRedisTemplate.opsForValue()
                    .get(redisKey);
            if (!StrUtil.equals(jwt, redisToken)) {
                throw new AuthException("Token 信息异常");
            }
            return claims.getSubject();
        } catch (JwtException e) {
            log.error("Token 数据异常，解析失败");
            throw new AuthException("Token 数据异常，解析失败");
        }
    }

}
